﻿using System.Text;
using System.Threading.Tasks;
using System;
using System.Buffers;

namespace SuperSocketService
{
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Logging;
    using SuperSocket;
    using SuperSocket.ProtoBase;
    using System.Collections.Generic;
    using System.Linq;

    public class MyFilterFactory : CommandLinePipelineFilter
    {
        public override StringPackageInfo Filter(ref SequenceReader<byte> reader)
        {
            StringPackageInfo stringPackageInfo = new StringPackageInfo();

            stringPackageInfo.Key = reader.ReadString();

            return stringPackageInfo;

            //return base.Filter(ref reader);
        }
    }

    class Program
    {
        static async Task Main(string[] args)
        {

            var host = SuperSocketHostBuilder
                        .Create<StringPackageInfo, MyFilterFactory>()
                        .UsePackageHandler(async (s, p) =>
                        {
                            var result = 0;

                            switch (p.Key.ToUpper())
                            {
                                case ("ADD"):
                                    result = p.Parameters
                                        .Select(p => int.Parse(p))
                                        .Sum();
                                    break;

                                case ("SUB"):
                                    result = p.Parameters
                                        .Select(p => int.Parse(p))
                                        .Aggregate((x, y) => x - y);
                                    break;

                                case ("MULT"):
                                    result = p.Parameters
                                        .Select(p => int.Parse(p))
                                        .Aggregate((x, y) => x * y);
                                    break;
                            }

                            await s.SendAsync(Encoding.UTF8.GetBytes(result.ToString() + "1\r\n"));
                        })
                        .ConfigureSuperSocket(options =>
                        {
                            options.Name = "Echo Server";
                            options.Listeners = new[] {
                                new ListenOptions
                                {
                                    Ip = "Any",
                                    Port = 4040
                                }
                            };
                        })
                        .ConfigureLogging((hostCtx, loggingBuilder) =>
                        {
                            loggingBuilder.AddConsole();
                        })
                        .Build()
                        ;

            await host.RunAsync();

        }
    }
}
